﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        //私钥
        private static string privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCc540quYC9xzCMZeFOe8UmE3W5LWrqFd/2DDSHQASxq8vmOiwFRSG2hsVXtjfmNLQNhtpTR0SGDUjkCsx+SJH0JDnOfQ2xXHasO65Rnv2wrHs64P6U0aUrMWjgapjkmLwzRV12AKNAX77MGIocpcB0KZhk+0AVc6oQCBybV65JTGu+pAyFLMJRtIP5kH3VMuXmig6VeiZAsjEewD/emxgK3cXejMQvqlNYFnCLsZ7ovAhr+bhz6SHkOws3p80O6zfQbKfLzdSVaZK8FnwNPznUxAK77bRZN0zF3V9mL9+zrarvFPD5VkcVHNLj0DRzLmr2c5TbiCigs4+I+NMfhpoLAgMBAAECggEAbM8GzoImDXV87WAZhtu+NFF6ahhc9EiHL5H3O3PhzXRdyiK9NEpkvrdnUxRCX5pc4qSJ8waRNoUv7zSt60VYMf6NN+zw+fYtNfONR30CYOq76nDtGzbnW7TADiDeNmjU2plX3uVCUPoUzmSWIpevht7xl9XE8xtq7AM0E2YSrzEADcxtqQslM0uVOf+ki1eu0/OwCz13FzPlPtnDwt2Lw9xxCxWqTgpN4oD5m6EWTqbognUIJ0EFD0dHXjrYnHXc+/Za5e+CDXYApHuhR9bifa1e4HMN084oLY+rkSXUV3+Te0APPCfbeEeqvubziDmKxxKaWUq1wPbYi4c06ZQdgQKBgQDhF7zDWgiJFTgrLGmExJRKiR/3QZN4sugYE1itdRDJmiPV4xhWPXSsND3WtqR5+0otb/hbzRa3cyl/RXV/1ZmBbE46fX2DKnmLQ1gP74iOuqWpfxjh/qpk+3kEY9aP57le/O0QEEPsJmqCsGM7XnzfNsxGAFYaDHooRbcGtv++AwKBgQCycuvRUQjV4dxTuRJuwFbmdq4odSBMu7yCS4i5I9I73d3TGZBWfiXQWFmuiPh+pf3HdvMbgyA243Uv/NGapSmNvARXm0/eEyfTxV7+GVdwLf3sSe8DQMCR1eJA9VzuS+jhCrHkFgyW3V/3ki66W8YITENlgC+VebOatfFE8i/ZWQKBgQCZ2VmhxFX1LFW53J86qgoZb+QzYdTkOJQ+cGq6FDunL/2yYYfu2g527TYfHbMJ1OH8cH22cVVHiiUg4l7PQzWqqlZF0CQLlOqCb0MvkS8rLxOv6DkfrqrUXrV2dK7gqSegbwuxYQyryg4eyWTp3UlIX/H7Hpu7LjAIeq4Anu/p9QKBgFMtpiYHM6segGi2F5VwKhF6uGs7TTb3O0MwmiZSQCiPnlpLzC/E1TNsO0FTryC5lrVnCKKGWHm9RF595eXDnr7mKM/9IRlOrH3VvhWLEmrDxVxiifpmMFzJ6ZCFzi91SrO7HHhIns2jmpv3k7hiFsi/Y5roSUXPWJyAull82jjhAoGAaKujjF4HL91UXZFetkkKiBIpIrH5+XbiX9z7H9/Tv8NSy/zTvXp3hFl3dr9gO722i/96dTq4th23Gqtih4cA9x8Wd7RChR9yAK/ffSj1lW6RhBWj1j2JCPFCm1TJD5iO3bIeuHm2sAuafKKoWT/VCUkKRwt9Wwh9yF20vMQ3kFw=";
        //公钥
        private static string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjutZyxP2L9eYM6DhZ11jk5lZieyyA6Wsr4baAU7PT+E0fv3KlERoh0edHLsLVff2I4AzuEqSoKDywKIBw1aSkIXGAaESj/FzA/V1jtmorq1RpPFmaqAOGDocMiaqukBBemwFnsYrTegsZUf88fU7KujwEMffLhhpwnM/Vf0NJ2s3ZwEZCgPWDa5cm1YpMLgopzc5HozENI5K9VFL92ThjHiTiutE28Bpi2xgSt6Cx+S8Nxqhy6/r/YVxvfgP66YCccnWOObN3fWo5TXepP6uBReTwjqNajlcSC5JqINqUUEAqief87y3NAFKRbE7Bu312y6zqcJgC/TIrWLXXB1/XQIDAQAB";

        private static string orderQueryUrl = "https://api.cmburl.cn:8065/polypay/v1.0/mchorders/orderquery";

        private static string qrCodeapplyUrl = "https://api.cmburl.cn:8065/polypay/v1.0/mchorders/qrcodeapply";

        private static string notifyUrl = "https://www.baidu.com";

        private static string appId = "8ab74856-8772-45c9-96db-54cb30ab9f74";

        private static string appSecret = "5b96f20a-011f-4254-8be8-9a5ceb2f317f";

        private static void OrderQueryDemo()
        {
            //业务要素
            Dictionary<string, string> requestTransactionParams = new Dictionary<string, string>();
            requestTransactionParams.Add("merId", "30899917012000T");   //商户号(必传)
            requestTransactionParams.Add("cmbOrderId", "100419070210595371147326");  //平台订单号
            requestTransactionParams.Add("orderId", "1562036392778"); //商户订单号(必传)
            requestTransactionParams.Add("userId", "N002852494");   //收银员(必传)

            string signResult = SignatureUtil.SignMethod(requestTransactionParams, privateKey);

            JavaScriptSerializer jss = new JavaScriptSerializer();//仅作展示，这个方法用于解析json可能有性能问题
            Dictionary<string, string> signResultMap = jss.Deserialize<Dictionary<string, string>>(signResult);
            
            // 组apiSign加密Map
            Dictionary<string, string> apiSign = new Dictionary<string, string>();
            apiSign.Add("appid", appId);
            apiSign.Add("secret", appSecret);
            apiSign.Add("sign", signResultMap["sign"]);
            apiSign.Add("timestamp", "" + ConvertDateTime(System.DateTime.Now) / 10000000);

            // MD5加密
            String MD5Content = SignatureUtil.GetSignContent(apiSign);
            String apiSignString = MD5Util.GetMD5(MD5Content, "UTF-8");

            // 组request头部Map
            Dictionary<string, string> apiHeader = new Dictionary<string, string>();
            apiHeader.Add("appid", appId);
            apiHeader.Add("timestamp", "" + ConvertDateTime(System.DateTime.Now) / 10000000);
            apiHeader.Add("apisign", apiSignString);

            // 发送HTTP post请求
            Dictionary<string, string> response = WebUtil.PostForEntity(orderQueryUrl, signResult, apiHeader);
            if (response == null)
            {
                return;
            }

            // 返回结果验签
            Boolean checkResult1 = SignatureUtil.CheckSign(jss.Serialize(response), publicKey);
            if(!checkResult1){
                return;
            }

            String success = response["returnCode"];
            Console.WriteLine("返回结果：" + success);
        }

         public static void QrCodeApplyDemo(){
            //业务要素
            Dictionary<string, string> requestTransactionParams = new Dictionary<string, string>();
            requestTransactionParams.Add("body", "聚合支付测试");   //商户号(必传)
            requestTransactionParams.Add("currencyCode", "156");    //交易币种，默认156，目前只支持人民币（156）
            requestTransactionParams.Add("merId", "30899917012000T");   //商户号(必传)
            requestTransactionParams.Add("notifyUrl", notifyUrl);  //交易通知地址(必传)
            requestTransactionParams.Add("orderId", "" + ConvertDateTime(System.DateTime.Now) / 10000000); //商户订单号(必传)
            requestTransactionParams.Add("payValidTime", "1200"); //支付有效时间
            requestTransactionParams.Add("termId", "00774411");  //终端号
            requestTransactionParams.Add("txnAmt", "1405");  //交易金额,单位为分(必传)
            requestTransactionParams.Add("userId", "N002852494");   //收银员
            // 组装requestBody并加签
            string signResult = SignatureUtil.SignMethod(requestTransactionParams, privateKey);

            JavaScriptSerializer jss = new JavaScriptSerializer();
            Dictionary<string, string> signResultMap = jss.Deserialize<Dictionary<string, string>>(signResult);

            // 组apiSign加密Map
            Dictionary<string, string> apiSign = new Dictionary<string, string>();
            apiSign.Add("appid", appId);
            apiSign.Add("secret", appSecret);
            apiSign.Add("sign", signResultMap["sign"]);
            apiSign.Add("timestamp", "" + ConvertDateTime(System.DateTime.Now) / 10000000);

            // MD5加密
            String MD5Content = SignatureUtil.GetSignContent(apiSign);
            String apiSignString = MD5Util.GetMD5(MD5Content, "UTF-8");

            // 组request头部Map
            Dictionary<string, string> apiHeader = new Dictionary<string, string>();
            apiHeader.Add("appid", appId);
            apiHeader.Add("timestamp", "" + ConvertDateTime(System.DateTime.Now) / 10000000);
            apiHeader.Add("apisign", apiSignString);

            // 发送HTTP post请求
            Dictionary<string, string> response = WebUtil.PostForEntity(qrCodeapplyUrl, signResult, apiHeader);

            // 返回结果验签
            Boolean checkResult1 = SignatureUtil.CheckSign(jss.Serialize(response), publicKey);
            if(!checkResult1){
                return;
            }

            String success = response["returnCode"];
            Console.WriteLine("返回结果：" + success);
        }

        private static long ConvertDateTime(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            return time.Ticks - startTime.Ticks;
        }

        static void Main(string[] args)
        {
            QrCodeApplyDemo();
            Console.WriteLine("-------------------------------------------------------------------------");
            OrderQueryDemo();
        }
    }
}
